# -*- coding : utf-8 -*-
# @Time    : 2023/6/7 10:29
# @Author  : wanggang
# @Email   : wanggang2@lingxi.ai
# @File    : LLm_server.py
# @Software: LLM_server_v2.0

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import sys
sys.path.append('../internal_server/')
import json
import asyncio
import time

import tornado.web
import tornado.ioloop
import tornado.options
import tornado.httpserver
import tornado.httpclient
from tornado import netutil, httpserver, ioloop, web, process
from tornado.options import define
from tornado.options import options

from abc import ABC
from urllib.parse import parse_qs
import settings
from dialogue.service.dialogue_service import dialogueService


dialogService = dialogueService()
define("port", default=settings.CREDIT_PORT, help="run on the given port", type=int)

class DialogueStartHandler(tornado.web.RequestHandler, ABC):

    async def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        dialogue_id = self.get_argument('dialogueId')
        user_id = self.get_argument('userId')
        dialogue_info = await dialogService.start(session_id, workspace_id, dialogue_id, user_id)
        self.write(json.dumps(dialogue_info.get("reply"), ensure_ascii=False))


class DialogueProcessHandler(tornado.web.RequestHandler, ABC):

    async def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        query = self.get_argument('query')
        is_try = self.get_argument('isTry', "false")
        break_param = self.get_argument('breakParam', "")

        dialogue_info = await dialogService.process(session_id, workspace_id, query, is_try, break_param)
        self.write(json.dumps(dialogue_info.get("reply"), ensure_ascii=False))
        pass

    async def post(self):
        session_id = self.get_body_argument("sessionId")
        workspace_id = self.get_body_argument("workspaceId")
        query = self.get_body_argument("query")
        is_try = self.get_body_argument("isTry", "false")
        break_param = self.get_body_argument("breakParam", "")
        settings.log.info("")
        dialogue_info = await dialogService.process(session_id, workspace_id, query, is_try, break_param)
        self.write(json.dumps(dialogue_info.get("reply"), ensure_ascii=False))


class DialogueStartForOutboundHandler(tornado.web.RequestHandler, ABC):

    async def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        dialogue_id = self.get_argument('dialogueId')
        user_id = self.get_argument('userId')
        dialogue_start = await dialogService.start(session_id, workspace_id, dialogue_id, user_id)
        result = {"result": dialogue_start, "retCode": 200, "errMsg": ""}
        self.write(json.dumps(result, ensure_ascii=False))


class DialogueProcessNewHandler(tornado.web.RequestHandler, ABC):

    async def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        query = self.get_argument('query')
        is_try = self.get_argument('isTry', "false")
        break_param = self.get_argument('breakParam', "")

        dialogue_info = await dialogService.process(session_id, workspace_id, query, is_try, break_param)
        result = {"result": dialogue_info, "retCode": 200, "errMsg": ""}
        self.write(json.dumps(result, ensure_ascii=False))


class DialogueHandleMissRecordHandler(tornado.web.RequestHandler, ABC):

    def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        query = self.get_argument('query')
        handleRecord = dialogService.handleMissRecord(session_id, workspace_id, query)
        result = {"result": handleRecord, "retCode": 200, "errMsg": ""}
        self.write(json.dumps(result, ensure_ascii=False))


class DialogueEndHandler(tornado.web.RequestHandler, ABC):

    def get(self):
        session_id = self.get_argument('sessionId')
        workspace_id = self.get_argument('workspaceId')
        end_msg = "end"
        retCode = "200"
        dialogService.end(session_id, workspace_id)
        result = {"result": end_msg, "retCode": 200, "errMsg": ""}
        self.write(json.dumps(result, ensure_ascii=False))


class Handle(tornado.web.RequestHandler):

    # 功能函数
    def run(self):
        pass

    # get请求入口
    def get(self):
        self._get_queries()

    # post请求入口
    def post(self):
        self._post_queries()

    # get请求获取参数
    def _get_queries(self):
        arg_1 = self.get_argument('arg_1', '')
        arg_2 = self.get_argument('arg_2', '')

        return arg_1, arg_2

    # post请求获取灿谁
    def _post_queries(self):
        arg = json.loads(self.request.body)
        arg_1 = arg['arg_1']
        arg_2 = arg['arg_2']

        return arg_1, arg_2


class searchKnowledgeHandle(tornado.web.RequestHandler, ABC):

    async def get(self):
        query = self.get_argument('query')
        dialogue_id = self.get_argument('dialogueId')
        user_situation = eval(self.get_argument('userSituation', ''))

        knowledge_json = await dialogService.search_knowladge(dialogue_id, query, user_situation)

        self.write(json.dumps(knowledge_json, ensure_ascii=False))



if __name__ == '__main__':
    # 启动服务
    # 2 A100 支持 QPS 10 process
    # 单卡多进程
    # 单次多请求 batch 发送逻辑
    settings.log.info("启动服务...")
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[
        (r'/original', Handle),
        (r'/dialogue/start', DialogueStartHandler),
        (r'/dialogue/process', DialogueProcessHandler),
        (r'/dialogue/startForOutbound', DialogueStartForOutboundHandler),
        (r'/dialogue/processNew', DialogueProcessNewHandler),
        (r'/dialogue/handleMissRecord', DialogueHandleMissRecordHandler),
        (r'/dialogue/end', DialogueEndHandler),
        (r'/searchKnowladge', searchKnowledgeHandle),
        ],
        # autoreload=False,
        debug=False,
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.bind(options.port)
    http_server.start(settings.CREDIT_PROCESSING_NUM)

    # sockets = tornado.netutil.bind_sockets(settings.PORT)
    # tornado.process.fork_processes(settings.PROCESSING_NUM)
    # http_server.add_sockets(sockets)

    # app.listen(8899)
    settings.log.info("端口：{}...".format(settings.CREDIT_PORT))
    tornado.ioloop.IOLoop.instance().start()
    # tornado.ioloop.IOLoop.current().start()
    # message = {
    #     "msgContent": "测试数据4",
    #     "workspaceId": 55369,
    #     "speakerType": "IVR",
    #     "sessionId": "0-2120-671322255-1667158375230459904-490",
    #     "msgTime": ""
    # }
    # myKafkaConsumer.consumerMessages()
    # time.sleep(2)
    # myKafkaProducer.sendMessages(message)
